package org.example.common.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.example.common.exception.LeaseException;
import org.example.lease.model.result.ResultCodeEnum;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author 宋孟林
 * @description
 * @date: 2025/5/25 10:06
 */
public class JWTUtil {

    private static long tokenExpiration = 60 * 60 * 1000L;
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    /**
     * jwt包含三部分，头部---负载(playload --- claim)---签名
     *
     * @param userId   id
     * @param username id
     * @return token
     */
    public static String createToken(Long userId, String username) {
        return Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", userId).
                claim("username", username).
                signWith(tokenSignKey).
                compact();
    }

    /**
     * 验证jwt的合法性
     * 获取负载 claim
     *
     * @param token token
     * @return claims
     */
    public static Claims parseToken(String token) {
        if (token == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}